package org.jakim.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.jakim.db.HibernateUtil;
import org.jakim.entity.User;

/**
 * Servlet implementation class login
 */

public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Login() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String userName = request.getParameter("userEmail");
		String userPassword = request.getParameter("userPassword");

		if (userPassword.isEmpty() || userPassword.length() < 4) {
			return;
		}

		Session hibernateSession = HibernateUtil.getSessionFactory()
				.openSession();
		hibernateSession.beginTransaction();
		Criteria userCriteria = hibernateSession.createCriteria(User.class);

		User user = (User) userCriteria.add(
				Restrictions.and(Restrictions.eq("userEmail", userName),
						Restrictions.eq("userPassword", userPassword)))
				.uniqueResult();

		if (user == null) {
			hibernateSession.close();
			return;
		}

		hibernateSession.close();

		HttpSession httpSeesion = request.getSession();

		httpSeesion.setAttribute("User", user);
		response.sendRedirect("userhome.jsp");
	}

}
